//
//  IALessionViewController.m
//  VoiceClass
//
//  Created by caoxiaobo on 2017/12/3.
//  Copyright © 2017年 YRX. All rights reserved.
//

#import "IALessonViewController.h"
#import "IASubjectItem.h"
#import <iflyMSC/IFlyMSC.h>
#import "IATConfig.h"
#import "ISRDataHelper.h"
#import "IANPLSimilarityService.h"
#import "StudentViewController.h"
#import "MBProgressHUD.h"
#import "Definition.h"
#import "IAStudent.h"
#import "IAMetaDataReader.h"
#import "IAStudent.h"
#import "IALabel.h"

static const CGFloat kDefaultLabelH = 54.0f;
static const CGFloat kMargin = 12.0f;
static const CGFloat kTopMargin = 12.0f;

@interface IALessonViewController ()

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UITableViewCell *studentCell;
@property (nonatomic, strong) IALabel *questionLabel;
@property (nonatomic, strong) UIView *resultView;
@property (nonatomic, assign) CGFloat initialScrollContentHeight;

@property (nonatomic, strong) NSMutableString *speechContent;
@property (nonatomic, strong) NSString *studentAnswer;

@property (nonatomic, strong) NSString *currentRigthRate;

@property (nonatomic, strong) IAStudent *answeredStudent;

@end

@implementation IALessonViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"语音答题";
    self.answerLabelButton.text = @"按住答题";
    
    UIBarButtonItem *saveItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveResult)];
    self.navigationItem.rightBarButtonItem = saveItem;
    
    [self setupSubViews];
}

- (void)setupSubViews {
    UIScrollView *scrollView = [UIScrollView new];
    [self.view addSubview:scrollView];
    self.scrollView = scrollView;
    CGFloat viewW = self.view.bounds.size.width;
    CGFloat viewH = self.view.bounds.size.height;
    CGFloat scrollViewY = 64.0f;
    CGFloat scrollViewW = viewW;
    CGFloat scrollViewH = viewH - kLabelButtonH - scrollViewY;
    if (@available(iOS 11.0, *)) {
        scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    scrollView.frame = CGRectMake(0, scrollViewY, scrollViewW, scrollViewH);
    scrollView.alwaysBounceVertical = YES;
    
    // 添加回答问题的学生
    {
        if (self.suggestStudent) {
            self.answeredStudent = self.suggestStudent;
        } else {
            NSArray <IAStudent *> *students = [IAMetaDataReader getStudents];
            uint32_t random = arc4random() % students.count;
            if (random >= students.count || random <= 0) {
                random = 0;
            }
            self.answeredStudent = students[random];
        }
        
        self.studentCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@""];
        self.studentCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        self.studentCell.frame = CGRectMake(0, kTopMargin, scrollView.cWidth, 54);
        self.studentCell.textLabel.text = [NSString stringWithFormat:@"%@", self.answeredStudent.name];
        self.studentCell.detailTextLabel.text = @"(默认推荐答题较少的同学)  重新选择";
        self.studentCell.detailTextLabel.font = [UIFont systemFontOfSize:13.0];
        self.studentCell.imageView.image = [UIImage imageNamed:self.answeredStudent.avatar];
        self.studentCell.imageView.clipsToBounds = YES;
        self.studentCell.imageView.contentMode = UIViewContentModeScaleToFill;
        self.studentCell.backgroundColor = CMNormalBg;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseStudent)];
        [self.studentCell addGestureRecognizer:tapGesture];
        [scrollView addSubview:self.studentCell];
    }
    
    CGFloat labelW = scrollViewW - 2 * kMargin;
    NSString *question = self.subject.question;
    // question
    if (question.length > 0) {
        CGFloat labelH = self.view.cHeight - CGRectGetMaxY(self.studentCell.frame) - kDefaultLabelH - kTopMargin;
        self.questionLabel.text = question;
        self.questionLabel.frame = CGRectMake(kMargin, CGRectGetMaxY(self.studentCell.frame) + kTopMargin, labelW, labelH);
        self.questionLabel.topInset = 36.0;
        self.questionLabel.verticalAlignment = IAVerticalAlignmentTopArea;
        [scrollView addSubview:self.questionLabel];
    }
    [scrollView addSubview:self.resultView];
    self.resultView.hidden = NO;
    self.initialScrollContentHeight = scrollView.contentSize.height;
}

- (CGFloat)assembleResultView:(CGFloat)maxY {
    NSString *question = self.subject.question;
    NSString *correctAnswer = self.subject.answer;
    
    UILabel *label1 = [self assembleLable:18.0f textColor:HEXCOLOR(0x333333) bold:NO];
    UILabel *label2 = [self assembleLable:20.0f textColor:HEXCOLOR(0x000030) bold:YES];
    UILabel *label3 = [self assembleLable:18.0f textColor:HEXCOLOR(0x333333) bold:NO];
    UILabel *label4 = [self assembleLable:20.0f textColor:HEXCOLOR(0x000030) bold:YES];
    UILabel *label5 = [self assembleLable:18.0f textColor:HEXCOLOR(0x333333) bold:NO];
    UILabel *label6 = [self assembleLable:20.0f textColor:HEXCOLOR(0x000030) bold:YES];
    UILabel *label7 = [self assembleLable:18.0f textColor:HEXCOLOR(0x333333) bold:NO];
    UILabel *label8 = [self assembleLable:24.0 textColor:[UIColor redColor] bold:YES];
    label1.text = @"问题:";
    label2.text = question;
    label3.text = @"标准答案:";
    label4.text = correctAnswer;
    label5.text = @"学生回答:";
    label6.text = self.studentAnswer;
    label7.text = @"正确率:";;
    label8.text = self.currentRigthRate;
    
    UIView *view1 = [self assembleContainer:CMNormalBg];
    UIView *view2 = [self assembleContainer:CMNormalBg];
    [self.resultView addSubview:view1];
    [self.resultView addSubview:view2];
    
    [view1 addSubview:label1];
    [view1 addSubview:label2];
    [view1 addSubview:label3];
    [view1 addSubview:label4];

    [view2 addSubview:label5];
    [view2 addSubview:label6];
    [view2 addSubview:label7];
    [view2 addSubview:label8];
    
    // 布局
    CGFloat scrollViewW = self.scrollView.cWidth;
    CGFloat lastHeight = 0.0f;
    CGFloat const constWidth = scrollViewW;
    CGFloat const lrMargin = 12.0f;
    CGFloat const udMargin = 8.0f;
    CGFloat const constLabelH = 24.0f;
    
    CGFloat labelW = constWidth - 2 * lrMargin;
    CGFloat questionlabelH = [question boundingRectWithSize:CGSizeMake(labelW, CGFLOAT_MAX)
                                                    options:NSStringDrawingUsesLineFragmentOrigin
                                                 attributes:@{NSFontAttributeName : label2.font}
                                                    context:nil].size.height;
    
    CGFloat correctlabelH = [correctAnswer boundingRectWithSize:CGSizeMake(labelW, CGFLOAT_MAX)
                                                        options:NSStringDrawingUsesLineFragmentOrigin
                                                     attributes:@{NSFontAttributeName : label4.font}
                                                        context:nil].size.height;
    
    CGFloat userAnswerlabelH = [self.studentAnswer boundingRectWithSize:CGSizeMake(labelW, CGFLOAT_MAX)
                                                                options:NSStringDrawingUsesLineFragmentOrigin
                                                             attributes:@{NSFontAttributeName : label6.font}
                                                                context:nil].size.height;
    
    label1.frame = CGRectMake(lrMargin, udMargin, labelW, constLabelH);
    label2.frame = CGRectMake(lrMargin, CGRectGetMaxY(label1.frame) + udMargin, labelW, questionlabelH);
    label3.frame = CGRectMake(lrMargin, CGRectGetMaxY(label2.frame) + udMargin, labelW, constLabelH);
    label4.frame = CGRectMake(lrMargin, CGRectGetMaxY(label3.frame) + udMargin, labelW, correctlabelH);
    view1.frame = CGRectMake(0, 0, scrollViewW, CGRectGetMaxY(label4.frame) + udMargin);
    
    lastHeight += view1.cHeight;
    lastHeight += udMargin * 2;
    
    label5.frame = CGRectMake(lrMargin, udMargin, labelW, constLabelH);
    label6.frame = CGRectMake(lrMargin, CGRectGetMaxY(label5.frame)+ udMargin, labelW, userAnswerlabelH);
    label7.frame = CGRectMake(lrMargin, CGRectGetMaxY(label6.frame)+ udMargin, 60.0, constLabelH);
    label8.frame = CGRectMake(CGRectGetMaxX(label7.frame) + lrMargin, label7.cY, 120.0f, constLabelH);
    view2.frame = CGRectMake(0, lastHeight, scrollViewW, CGRectGetMaxY(label8.frame) + udMargin);
    lastHeight += view2.cHeight;
    
    self.resultView.frame = CGRectMake(0, maxY, scrollViewW, lastHeight);
    
    if ([self.answerLabelButton.text isEqualToString:@"按住答题"]) {
        self.answerLabelButton.text = @"重新答题";
    }
    return CGRectGetMaxY(self.resultView.frame);
}

- (void)adaptiveScrollViewContentSizeWithMaxHeight:(CGFloat)maxHeight {
    CGFloat viewW = self.view.bounds.size.width;
    if (maxHeight > self.initialScrollContentHeight) {
        [self.scrollView setContentSize:CGSizeMake(viewW, maxHeight)];
    } else {
        [self.scrollView setContentSize:CGSizeMake(viewW, self.initialScrollContentHeight)];
    }
}

- (void)reBeginOnView {
    self.questionLabel.hidden = NO;
    self.resultView.hidden = YES;
    CGFloat viewW = self.view.bounds.size.width;
    [self.scrollView setContentSize:CGSizeMake(viewW, self.initialScrollContentHeight)];
}

- (void)reLayoutSubviews {
    [self.resultView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    self.resultView.hidden = NO;
    self.questionLabel.hidden = YES;
    CGFloat maxY = CGRectGetMaxY(self.studentCell.frame) + kTopMargin;
    maxY = [self assembleResultView:maxY];
    [self adaptiveScrollViewContentSizeWithMaxHeight:maxY];
}

- (void)chooseStudent {
    NSArray <IAStudent *> *students = [IAMetaDataReader getStudents];
    StudentViewController *studentController = [[StudentViewController alloc] initWithStudents:students];
    studentController.selectedHandler = ^(IAStudent *student) {
        if (student) {
            self.answeredStudent = student;
            self.studentCell.textLabel.text = [NSString stringWithFormat:@"学生：%@", self.answeredStudent.name];
            self.studentCell.imageView.image = [UIImage imageNamed:self.answeredStudent.avatar];
            [self reBeginOnView];
        }
    };
    [self.navigationController pushViewController:studentController animated:YES];
}

- (void)saveResult {
    if (!self.studentAnswer) {
        // 没有答题
        [self showErrorHud:@"还没有答题, 保存无效"];
        return;
    }
    
    if (!self.currentRigthRate) {
        // 没有答题
        [self showErrorHud:@"没有有效的正确率, 保存无效"];
        return;
    }
    
    IASubjectAnswerResult *result = [[IASubjectAnswerResult alloc] init];
    result.student = self.answeredStudent;
    result.subjectItem = self.subject;
    result.goal = self.currentRigthRate;
    result.studentAnswer = self.studentAnswer;
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [hud showAnimated:YES];
    [IAMetaDataReader saveSubjectResult:result completion:^(BOOL result) {
        hud.label.text = @"保存成功";
        [hud hideAnimated:YES afterDelay:1.0];
        if (self.resultDidUpdateBlock) {
            self.resultDidUpdateBlock();
            self.resultDidUpdateBlock = nil;
        }
    }];
}

- (void)longPress:(UILongPressGestureRecognizer *)gesture {
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan: {
            self.title = @"答题中...";
            [self reBeginOnView];
            self.speechContent = nil;
            self.studentAnswer = nil;
            [self startRecord];
            break;
        }
        case UIGestureRecognizerStateChanged: {
            break;
        }
            
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded: {
            self.title = @"语音答题";
            [self stopRecord];
            break;
        }
            
        case UIGestureRecognizerStateFailed: {
            self.title = @"语音答题";
            [self stopRecord];
            break;
        }
            
        default:
            break;
    }
}

#pragma mark - IFlySpeechRecognizerDelegate

- (void)onError:(IFlySpeechError *) errorCode {
    if (errorCode.errorCode != 0) { // 发生错误
        NSString *msg = errorCode.errorDesc;
        [self showErrorHud:msg];
    }
}

- (void)onResults:(NSArray *) results isLast:(BOOL)isLast {
    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *dic = results[0];
    for (NSString *key in dic) {
        [resultString appendFormat:@"%@",key];
    }
    
    NSString *resultFromJson =  [ISRDataHelper stringFromJson:resultString];
    if (resultFromJson) {
        [self.speechContent appendString:resultFromJson];
    }
    
    if (isLast) {
        if (self.speechContent.length > 0) {
            self.studentAnswer = [self.speechContent copy];
            [self checkSimilarity];
        } else {
            // 语言听写失败 可能是录音时间太短...
            [self showErrorHud:@"语言听写失败, 录音时间太短..."];
        }
    }
}

- (void)checkSimilarity {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.backgroundView.color = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.4];;
    [IANPLSimilarityService checkSimilarityBetweenText:self.subject.answer
                                       withAnotherText:self.speechContent
                                            completion:^(CGFloat rate) {
                                                [hud hideAnimated:YES];
                                                int rateP = (int)(rate * 100.0f);
                                                self.currentRigthRate = [NSString stringWithFormat:@"%@%%", @(rateP)];
                                                [self reLayoutSubviews];
                                            }];
}

- (UILabel *)assembleLable:(CGFloat)fontSize textColor:(UIColor *)tColor bold:(BOOL)bold {
    UILabel *aLabel = [UILabel new];
    aLabel.numberOfLines = 0;
    if (bold) {
        aLabel.font = [UIFont boldSystemFontOfSize:fontSize];
    } else {
        aLabel.font = [UIFont systemFontOfSize:fontSize];
    }
    aLabel.textColor = tColor;
    return aLabel;
}

- (UIView *)assembleContainer:(UIColor *)bgColor {
    UIView *aView = [[UIView alloc] init];
    aView.backgroundColor = bgColor;
    return aView;
}

- (IALabel *)questionLabel {
    if (!_questionLabel) {
        _questionLabel = [IALabel new];
        _questionLabel.numberOfLines = 0;
        _questionLabel.textAlignment = NSTextAlignmentCenter;
        _questionLabel.font = [UIFont boldSystemFontOfSize:21.0];
        _questionLabel.textColor = HEXCOLOR(0x000030);
    }
    return _questionLabel;
}

- (UIView *)resultView {
    if (!_resultView) {
        _resultView = [[UIView alloc] init];
        _resultView.backgroundColor = [UIColor whiteColor];
    }
    return _resultView;
}

- (NSMutableString *)speechContent {
    if (!_speechContent) {
        _speechContent = [NSMutableString string];
    }
    return _speechContent;
}

@end
